//
//  WBNetWorkManager+Extension.swift
//  DLSwift微博
//
//  Created by 丁浪涛 on 2016/11/13.
//  Copyright © 2016年 丁浪涛. All rights reserved.
//

import Foundation
//封装新浪微博的网络请求方法

extension  WBNetWorkManager
{
    //since_id 获取最新的 默认未0
     //max_id 获取旧的
    func  statusList(since_id: Int64 = 0,max_id: Int64 = 0,completion:@escaping (_ list :[[String: AnyObject]]?,_ isSuccess : Bool)->())
    {
    
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // swift 中 Int可以直接转换成AnyObject 但是int64 不行
        print()
        let parameters = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)" ]
 
        tokenRequest(URLString: urlString, parameters:parameters as [String : AnyObject]? , completion: { (json, isSuccess) in
             if isSuccess
             {
//                print((json as AnyObject))
                //从json中获取status 字典数组

                let result  = (json as? AnyObject)?["statuses"] as? [[String: AnyObject]]
                
                completion(_:result,_ : isSuccess)
            }
            
        })
    
    }

    //返回新浪微博的未读数量
    func  unreadCount(completion:@escaping (_ count : NSInteger)->())
    {
        guard let uid = userAccount.uid else
        {
            return
        
        }
        let params = ["uid": uid]
        let urlStr  = "https://rm.api.weibo.com/2/remind/unread_count.json"
   
        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?, completion:{ (json,issuccess ) in
        let dict = json as? AnyObject
         let count  = dict?["status"]  as? Int ?? 0
            completion(count)
         print(json ?? "")
        })
    
    }

    // 获取用户信息接口
    func  loadUserInfo(completion:@escaping (_ dict : [String :AnyObject])->())
    {
        guard let uid = userAccount.uid else
        {
        return
        }
        
        let params = ["uid" : uid]
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?){(json: Any,isSuccess: Bool)->() in
        
            completion( (json as? [String :AnyObject]) ?? [:])
        }
        
    
    }
    
    
}
// OAuth相关
extension WBNetWorkManager
{
    // 请求OAuth授权
    //https://api.weibo.com/oauth2/authorize   
    //client_id：AppKey ：3954863772
    //redirect_uri ：http://baidu.com
    //appsecret :987e5825bdb0c9a4e9ae2827847afe52
    //获取
    //https://api.weibo.com/oauth2/access_token

    func  loadAccessToken(code: String,completion:@escaping (_ isSuccess : Bool)->())
     {
        
        let params = ["client_id": WBAppKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURL]
        let urlStr  = "https://api.weibo.com/oauth2/access_token"
        
        //发起网络请求
        request(method: .POST, URLString: urlStr , parameters: params as [String : AnyObject], completion: { (json,issuccess ) in
        
            
                let  access_token = (json as AnyObject)["access_token"] as! String
                print("access_token :\(access_token)")
                
                self.userAccount.yy_modelSet(withJSON: (json as? [String: Any]) ?? [:])
                print(self.userAccount)
           
                self.loadUserInfo{(dict :[String :AnyObject])->() in
                
                print(dict)
                    
                    //使用用户字典 设置用户账户信息
                self.userAccount.yy_modelSet(with: dict)
               print(self.userAccount)
                self.userAccount.saveAccount()
                completion(issuccess)
            }
     
            
        })
    }

}
